<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace app\cardeadmin\controller;

use app\common\controller\AdminController;
use app\common\model\ManageLog;
use app\common\model\Setting as SettingModel;
use think\facade\Console;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use app\api\controller\EmailSend;
use app\api\controller\OssUp;

/**
 * 平台设置
 * Class Setting
 * @package app\admin\controller
 */
class Setting extends AdminController
{
    /**
     * 平台设置
     * @author 救火队队长
     */
    public function index()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $model = new SettingModel();
            return $model->tableDataAdmin($data);
        }
        return View::fetch();
    }

    public function setAdd()
    {
        if($this->request->isPost()) {
            //header("HTTP/1.1 402"); exit;
            $model  = new SettingModel();
            $data   = input('param.');

            $list   = Db::name('setting')->where(['key'=> trim($data['key'])])->find();
            if($list) return $this->err('key already exist.');

            $re     = $model->setAdd($data);
            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Setting Add',
                    'content'   => ['key_name' => trim($data['key'])]
                ]);
                //配置保存后，清理缓存
                Cache::clear();//TODO 如果开启其他缓存，记得这里要配置缓存配置信息

                Console::call('sysClear', ['--cache', '--dir']);//清除缓存文件
                Console::call('sysClear', ['--path', ROOT_PATH . 'runtime\\cardeadmin\\temp\\']); //清除模板缓存
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        return View::fetch();
    }

    public function setEdit()
    {
        $model = new SettingModel();
        $id     = input('get.id');

        if($this->request->isPost()) {
            $data   = input('param.');
            if($data['key'] == 'oy_fund_user'){
                $key_name   = 'oy_user_up_email_' . $this->manage_id;
                $vercode = Cache::store('redis')->get($key_name);
                if($vercode != $data['vercode'] || empty($data['vercode'])){
                    return $this->err('vercode error');
                }
                Cache::store('redis')->delete($key_name);
            }
            $re     = $model->setEdit($data);
            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Setting Edit',
                    'content'   => ['set_id' => $data['set_id']]
                ]);
                //配置保存后，清理缓存
                Cache::clear();//TODO 如果开启其他缓存，记得这里要配置缓存配置信息

                Console::call('sysClear', ['--cache', '--dir']);//清除缓存文件
                Console::call('sysClear', ['--path', ROOT_PATH . 'runtime\\admin\\temp\\']); //清除模板缓存
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        $data= $model->find($id);
        View::assign([
            'data'          => $data
        ]);
        return View::fetch();
    }

    public function emailSend()
    {
        //获取随机6位字母
        $round_num     = nonceStr();
        $key_name   = 'oy_user_up_email_' . $this->manage_id;
        $email      = Db::name('manage')->where(['id'=>$this->manage_id])->value('email');
        Cache::store('redis')->set($key_name, $round_num , 60);
        $result     = EmailSend::sendEmail('oy_user_up_email_check' , [
            'email'     => $email ,
            'code'      => $round_num,
            'desc'      => 'user up email send vercode'
        ]);
        if($result){
            return json(['code'=>1,'msg'=>"Email verification code has been sent."]);
        }else{
            return json(['code'=>0,'msg'=>"Send mail failed!"]);
        }
    }

    public function  Uploads() {
        $file = request()->file('file');

        $suffix_list = explode("." , $file->getOriginalName());
        $suffix      = $suffix_list[1] ?? 'jpg';
        $result   = OssUp::fileUp([
            'type'      => 'document',
            'tmp_name'  => $file->getRealPath(),
        ],$suffix);
        $blog       = $result['blog'];
        $img_url    = $result['img_url'];
        if($blog){
            $img_name_list = explode('/',$img_url);
            $img_name      = !empty($img_name_list)? end($img_name_list):'';
            return json([
                'code'      => 1,
                'img_url'   => $img_url,
                'img_name'  => $img_name,
                'msg'       => 'upload success',
            ]);
        }else{
            return json([
                'code'      => 0,
                'img_url'   => '',
                'img_name'  => '',
                'msg'       => 'upload error',
            ]);
        }
    }

}